package org.serverct.finalfight.game.listener.gui;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.serverct.finalfight.game.GameManager;
import org.serverct.finalfight.game.gui.SpectatorTeleporter;

import java.util.HashSet;
import java.util.UUID;

public class SpectatorGuiListener implements Listener {
    public static HashSet<UUID> openers = new HashSet<>();

    @EventHandler
    public void onOpen(InventoryOpenEvent event) {
        if (event.getInventory().getHolder() instanceof SpectatorTeleporter.SpectatorGuiHolder) {
            openers.add(event.getPlayer().getUniqueId());
        }
    }

    @EventHandler
    public void onClose(InventoryCloseEvent event) {
        if (event.getInventory().getHolder() instanceof SpectatorTeleporter.SpectatorGuiHolder) {
            openers.remove(event.getPlayer().getUniqueId());
        }
    }

    @EventHandler
    public void onClickInv_1(InventoryClickEvent event) {
        Inventory inv = event.getClickedInventory();
        if (inv == null) {
            return;
        }
        Player player = (Player) event.getWhoClicked();
        if (openers.contains(player.getUniqueId())) {
            event.setCancelled(true);

            int slot = event.getSlot();
            if (slot < 0) {
                return;
            }
            ItemStack item = inv.getItem(slot);
            if (item == null) {
                return;
            }
            String name = item.getItemMeta().getDisplayName();
            Player goal = Bukkit.getPlayer(name.replace("§a✔存活: §e", "").replace("§c✖死亡: §e", ""));
            if (goal == null) {
                event.setCancelled(true);
            } else {
                event.setCancelled(true);
                player.teleport(goal);
            }
        }
    }

    @EventHandler
    public void onClickInv_2(InventoryClickEvent event) {
        Inventory inv = event.getClickedInventory();
        if (inv == null) {
            return;
        }
        Player player = (Player) event.getWhoClicked();
        int slot = event.getSlot();
        if (slot < 0) {
            return;
        }
        ItemStack item = inv.getItem(slot);
        if (item == null) {
            return;
        }
        if (item.equals(SpectatorTeleporter.menuItem)) {
            event.setCancelled(true);
            Inventory inventory = SpectatorTeleporter.generateInventory(GameManager.getGame(player));
            if (inventory == null) {
                return;
            }
            player.openInventory(inventory);
        }
    }
}
